package bspay

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/consts"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/bspay/bspay/tool"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type BspayPaymentNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// bspay代收回调通知
func NewBspayPaymentNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BspayPaymentNotifyLogic {
	return &BspayPaymentNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BspayPaymentNotifyLogic) BspayPaymentNotify(req *types.BspayPaymentNotifyReq) (resp *types.BspayPaymentNotifyResp, err error) {
	b, _ := sonic.Marshal(req)
	// 获取  配置信息
	conf, err := l.svcCtx.AssetsRpc.PayRecharge.RechargeChannelListByCode(l.ctx, &rpc.RechargeChannelByCodeRequest{Code: consts.BsPay})
	if err != nil {
		return nil, err
	}
	params := make(map[string]any)
	params["serial_id"] = req.SerialId
	params["ord_id"] = req.OrderNo
	params["amount"] = req.Amount
	params["recv"] = req.RecvAmount
	params["status"] = req.Status

	sign, err := tool.GenerateSignature(params, conf.SecretKey)

	if sign != req.Sign {
		logc.Error(l.ctx, "signature verification failed: ", sign, req.Sign)
		return nil, xerrors.ErrSignVerifyFailed
	}
	// 根据订单状态处理业务逻辑
	if req.Status == 1 {
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeSuccess(l.ctx, &rpc.NotifyOKRequest{OrderNo: req.OrderNo, ReturnJson: string(b)})
	} else {
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeFail(l.ctx, &rpc.NotifyFailRequest{OrderNo: req.OrderNo, ReturnJson: string(b)})
	}
	if err != nil {
		logc.Error(l.ctx, err, string(b))
	}
	return
}
